package com.onefinger.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.onefinger.aspect.Cache;
import com.onefinger.aspect.Uncache;
import com.onefinger.domain.CustomerTable;
import com.onefinger.domain.Device;
import com.onefinger.repository.GenericRepository;

public class CustomerTableService implements ICustomerTableService {

	@Autowired
	GenericRepository<CustomerTable> genericRepository; 

	@Autowired
	GenericRepository<Device> deviceRepository;

	private Long sessionId = 0L; 
	
	@Cache(cacheKey="customertables", expireTime=0)
	public List<CustomerTable> list() {
		return genericRepository.getList(CustomerTable.class);
	}

	
	@Uncache(cacheKey="customertables")
	public boolean save( CustomerTable customerTable ) {
		try {
			genericRepository.save(customerTable);
		} catch (Exception e) {
			
			return false;
		}
		return true;
	}

	@Uncache(cacheKey="customertables")
	public boolean remove(CustomerTable customerTable) {
		try {
			genericRepository.remove(customerTable);
		} catch (Exception e) {
			
			return false;
		}
		return true;
	}


	@Override
	@Uncache(cacheKey="customertables")
	public CustomerTable assignDevice(Long customerTableId, Long deviceId) {
		Device device = deviceRepository.find(Device.class, deviceId);
		CustomerTable customerTable = genericRepository.find(CustomerTable.class, customerTableId);
		
		customerTable.setDevice(device);
		
		save(customerTable);
		
		return customerTable;
	}


	@Override
	@Uncache(cacheKey="customertables")
	public CustomerTable changeStatus(Long customerTableId, String status) {
		CustomerTable customerTable = genericRepository.find(CustomerTable.class, customerTableId);
		// opening table...
		if( status.equals(CustomerTable.STATUS_OPEN) )
		{
			//Assert.assertEquals("La mesa debe estar cerrada para abrirla", CustomerTable.STATUS_CLOSE, customerTable.getStatus());
			customerTable.setSessionId(++sessionId);
		}

		if( status.equals(CustomerTable.STATUS_CLOSE) )
		{
			//Assert.assertEquals("La mesa debe estar abierta para cerrarla", CustomerTable.STATUS_OPEN, customerTable.getStatus());
			customerTable.setSessionId(0L);
		}
		
		customerTable.setStatus(status);
		save(customerTable);
		return customerTable;
	}


	public CustomerTable getCustomerTableByDevice( String mac ) {
		Device device = deviceRepository.find(Device.class, "mac", mac );
		if( device != null )
		{
			CustomerTable customerTable = genericRepository.find(CustomerTable.class, "device", device);
			return customerTable;
		} else {
			return null;
		}
			
	}

}
